package controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import pojo.Article;
import pojo.Menu;
import pojo.User;
import service.IArticleService;
import service.ICategoryService;
import service.IMenuService;
import service.IUserService;
import constant.Constant;
import util.PageModuleUtil;
import util.UploadFileUtil;
import util.Util;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/user")
public class UserController {
    @Autowired
    private IUserService userService;
    @Autowired
    private IArticleService articleService;
    @Autowired
    private ICategoryService categoryService;
    @Autowired
    private IMenuService menuService;
    /**
     * 用户登录页
     */
    @RequestMapping(value = "/login/",method = RequestMethod.GET)
    public String goLoginPage(HttpServletRequest request){
        if(request.getSession().getAttribute("user")!=null){
            return "redirect:/index";
        }
        return "user/login";
    }

    /**
     * 用户注册页
     * @return
     */
    @RequestMapping(value = "/reg/",method = RequestMethod.GET)
    public String goRegPage(){
        return "user/reg";
    }

    /**
     * 用户基本设置
     * @return
     */
    @RequestMapping(value = "/set/",method = RequestMethod.GET)
    public String goSetPage(HttpServletRequest request){
        PageModuleUtil.set(request,Constant.PAGE_USER);
        return "user/set";
    }

    /**
     * 用户主页
     * @param id
     * @return
     */
    @RequestMapping("/home/{id}/")
    public String goHomePage(@PathVariable(name = "id",required = true) int id, Model model,HttpServletRequest request){
        //获取该用户的所有信息
        //获取用户基本信息
        User user = userService.getUserById(id);
        if(user==null){
            //没有该用户信息，404
            return "other/404";
        }
        //获取用户最近写的帖子
        List<Article> articles = articleService.getArticlesByUserId(id);
        user.setUserArticles(articles);
        //获取用户最近的回复、评论

        //将用户信息放进视图
        model.addAttribute("user",user );
        //设置全局信息
        if(request.getSession().getAttribute("user")!=null){
            request.getSession().setAttribute("modulePage", Constant.PAGE_USER);
        }
        //如果是游客可以不设置全局信息
        return "user/home";
    }
    @RequestMapping("/message/")
    public String goMesPage(HttpServletRequest request,Model model){
        Util.setGeneralDataForView(categoryService, model);
        PageModuleUtil.set(request,Constant.PAGE_USER );
        return "user/message";
    }
    @RequestMapping("/post/")
    public String goPostPage(HttpServletRequest request,Model model){
        Util.setGeneralDataForView(categoryService, model);
        PageModuleUtil.set(request,Constant.PAGE_USER );
        return "user/post";
    }
    /**
     * 控制用户登录
     * @param mail
     * @param password
     * @param vercode
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/login/",method = RequestMethod.POST)
    public Map login(@RequestParam("email") String mail, @RequestParam("pass") String password, @RequestParam("vercode")String vercode, HttpServletRequest request){
        String code = (String) request.getSession().getAttribute("vercode");
        Map map = new HashMap();
        if(code!=null&&code.compareToIgnoreCase(vercode)==0){
            User user = userService.login(code,mail,password);
            if(user!=null){
                //获取用户可以操作的菜单项
                List<Menu> menus = menuService.getMenusByRoleId(user.getUserRoleId());
                user.setMenus(menus);
                //设置本次回话必须要全局信息
                request.getSession().setAttribute("user",user );
                //设置跳转页面需要用到的模块
                request.getSession().setAttribute("modulePage", Constant.PAGE_USER);
                //设置跳转的页面处理方式为跳转请求
                map.put("status", 0);
                //设置跳转请求的url
                map.put("action", "/index");
                request.getSession().removeAttribute("vercode");
                return map;
            }else {
                map.put("status",4 );
                map.put("msg","登录错误" );
                return map;
            }
        }else {
            map.put("status",5 );
            map.put("msg","验证码错误" );
            return map;
        }
    }
    /**
     * 控制用户退出
     * @param request
     * @return
     */
    @RequestMapping(value = "/logout")
    public String logout(HttpServletRequest request){
        String contextPath = request.getHeader("Referer");
        request.getSession().invalidate();
        return "redirect:"+contextPath;
    }

    /**
     * 修改用户个人信息
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/set/",method = RequestMethod.POST)
    public Map modifyInformation(User user,String pass,String repass,HttpServletRequest request){
        Map map = new HashMap();
        //处理用户修改个人信息
        if(user!=null){
            int i = userService.modifyInformationById(user);
            if(i==1){
                map.put("status",0 );
                User userById = userService.getUserById(user.getUserId());
                request.getSession().setAttribute("user",userById );
                return map;
            }
        }
        //处理用户修改密码
        if(pass!=null||repass!=null){
            if(!pass.equals(repass)){
                map.put("msg","两次密码不一致" );
                map.put("status",1 );
                return map;
            }
            //密码保存到数据库
            User userMessage = (User) request.getSession().getAttribute("user");
            userMessage.setUserPassword(pass);
            int i = userService.modifyPasswordById(userMessage);
            if(i==1){
                map.put("status",0 );
                return map;
            }
            map.put("status",1 );
            map.put("msg", "修改密码失败");
            return map;
        }
        map.put("code",2 );
        map.put("msg","修改失败" );
        return map;
    }
    @ResponseBody
    @RequestMapping(value = "/upload/")
    public Map modifyHeadImage(@RequestParam(name = "file",required = true) MultipartFile file,HttpServletRequest request){
        Map map = new HashMap();
        //获取上传头像的用户信息
        User user = (User) request.getSession().getAttribute("user");
        if(user==null){
            return null;
        }
        //设置存取路径
        String uploadPath = "/upload";
        //执行文件上传，并获得新的文件名
        String fileName = UploadFileUtil.upload(file, request, uploadPath);
        if (fileName == null){
            return null;
        }
        //更新数据库中的用户的头像信息
        user.setUserHeadImage(uploadPath+"/"+fileName);
        int i = userService.modifyHeadImgById(user);
        if(i==1){
            map.put("status",0 );
            map.put("count",0 );
            return map;
        }
        return null;
    }

    @ResponseBody
    @RequestMapping(value = "/reg/",method = RequestMethod.POST)
    public Map register(User user, String vercode, String pass, String repass, HttpServletRequest request){
        //返回前台的信息载体
        Map map = new HashMap();
        String code = (String) request.getSession().getAttribute("vercode");
        if(code==null){
            map.put("msg","请重新请求验证码" );
            map.put("status",1 );
            return map;
        }
        if(!code.equals(vercode)){
            map.put("msg","验证码错误" );
            map.put("status",1 );
            return map;
        }
        String mail = user.getUserMail();
        User userByMail = userService.getUserByMail(mail);
        if(userByMail!=null){
            map.put("msg","该邮箱已注册" );
            map.put("status",1 );
            return map;
        }
        String userName = user.getUserName();
        User userByName = userService.getUserByName(userName);
        if(userByName!=null){

        }
        if(!pass.equals(repass)){
            map.put("msg","密码不一致" );
            map.put("status",1 );
            return map;
        }
        user.setUserRoleId(2);
        user.setUserPassword(pass);
        user.setUserRegisterDate(new Date());
        int i = userService.addUser(user);
        if(i==1){
            map.put("status",0 );
            map.put("action", Constant.LOGIN_FIRST_PAGE);
            user = userService.getUserByMail(user.getUserMail());
            request.getSession().setAttribute("user",user );
            request.getSession().setAttribute("modulePage", Constant.PAGE_USER);
            return map;
        }
        map.put("status",1 );
        map.put("msg","服务异常，无法注册" );
        return map;
    }
}
